"""
全局fixture
"""
import os
import time
import random
import allure
import pytest
import json
import platform
from datetime import datetime
from faker import Faker



@pytest.fixture(scope='session')
def faker_factory():
    """Faker工厂fixture
    构造测试数据
    Returns:
        Faker: Faker实例"""
    return Faker('zh_CN')  # 中文环境数据


# === 全局配置钩子 ===
def pytest_configure(config):
    """配置全局参数"""
    # 设置测试环境
    env = config.getoption("--env", "dev")
    os.environ["TEST_ENV"] = env

    # 添加全局链接
    allure.dynamic.link("https://docs.example.com", name="系统文档")

    # 设置全局标记
    allure.dynamic.label("application", "erp-system")


# === 测试收集钩子 ===
def pytest_collection_modifyitems(config, items):
    """修改收集到的测试项"""
    # 为不同模块添加不同的Feature标签
    for item in items:
        if "test_login" in item.nodeid:
            allure.dynamic.label("feature", "用户认证")
            allure.dynamic.label("story", "登录功能")
        elif "test_payment" in item.nodeid:
            allure.dynamic.label("feature", "支付系统")
            allure.dynamic.label("story", "交易处理")

    # 随机失败测试用于演示(实际生产移除)
    for item in random.sample(items, min(2, len(items))):
        item.add_marker(pytest.mark.xfail(reason="演示随机失败"))


# === 测试执行钩子 ===
def pytest_runtest_setup(item):
    """测试设置阶段"""
    # 动态添加标题
    test_name = item.name.replace("_", " ").title()
    allure.dynamic.title(f"测试: {test_name}")

    # 添加开始时间标记
    item.start_time = datetime.now()


def pytest_runtest_call(item):
    """测试执行阶段"""
    # 添加步骤
    with allure.step("执行核心业务逻辑"):
        # 模拟一些测试操作
        time.sleep(0.1)
        # 随机添加附件
        if random.random() > 0.7:
            file_type = random.choice(["json", "txt", "html"])
            file_name = f"附件-{int(time.time())}.{file_type}"
            allure.attach(f"测试数据: {datetime.now()}", file_name, allure.attachment_type.TEXT)


def pytest_runtest_teardown(item, nextitem):
    """测试清理阶段"""
    # 添加持续时间
    duration = datetime.now() - item.start_time
    allure.dynamic.description(f"执行时间: {duration.total_seconds():.3f}秒")


# === 报告生成钩子 ===
def pytest_sessionfinish(session, exitstatus):
    """测试会话结束"""
    # 生成环境配置文件
    env_content = (
        f"env={os.getenv('TEST_ENV')}\n"
        f"os={os.name}\n"
        f"python.version={platform.python_version()}"
    )
    with open("allure/environment.properties", "w") as f:
        f.write(env_content)

    # 生成自定义分类文件
    categories = [
        {
            "name": "网络问题",
            "matchedStatuses": ["failed"],
            "traceRegex": ".*ConnectTimeout.*|.*ConnectionRefused.*"
        },
        {
            "name": "数据问题",
            "matchedStatuses": ["failed"],
            "messageRegex": ".*DataNotFound.*|.*InvalidDataFormat.*"
        }
    ]
    with open("allure/categories.json", "w") as f:
        json.dump(categories, f, indent=2)


# === 自定义装饰器替代方案 ===
def mark_description(desc):
    """动态添加描述的装饰器替代方案"""

    def decorator(func):
        def wrapper(*args, **kwargs):
            allure.dynamic.description(desc)
            return func(*args, **kwargs)

        return wrapper

    return decorator
